package com.study.exception;

import com.alibaba.fastjson.JSONObject;
import com.study.common.Result;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * 统一异常处理;
 * <p>
 *
 * </p>
 * @author niuxiaolong
 *
 * @create 20171129
 */
@ControllerAdvice
class GlobalExceptionHandler {

	public static final String DEFAULT_ERROR_VIEW = "error";

	/**
	 * 返回错误页面;
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", req.getRequestURL());
		mav.setViewName(DEFAULT_ERROR_VIEW);
		return mav;
	}

	/**
	 * 返回JSON错误提示信息;
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = UnauthorizedException.class)
	@ResponseBody
	public String jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {


		return JSONObject.toJSONString(new Result("500","没有权限"));
	}


}